<?php

namespace app\webapi\controller;

use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;
use OSS\Core\OssException;
use OSS\OssClient;
use think\facade\Db;
use think\facade\Request;
class ApiOss extends ApiBaseController
{
//    public $user_info = null;
//
//    public function __construct()
//    {
//        $this->user_info = $this->checkToken();
//        if (!preg_match('/^\d+$/', $this->user_info['id'])) {
//            $this->result_error('用户id出错');
//        }
//    }
    //"OssRegion": "oss-cn-beijing",
//"OssBucket": "ferr-neo",
//"OssAccessKeyId": "LTAI5tEUuTcqvvtcPCARvZcx",
//"OssAccessKeySecret": "n2cCzSPb3e3oKioTe5VgIlUppmB9Ec",
//"OssRoleArn": "acs:ram::1036562086512193:role/ferreira-neo",

    public static $ossBucket = 'vanxe';                 // OSS 配置改自己的  2022-11-13
    public static $ossRegion = 'oss-cn-beijing';
    public static $accessKeyId = 'LTAI5tGwu1KTEVtChWuuVPcZ';
    public static $accessKeySecret = '75RWzUzyERJK2bL50uzfu4TZ5IE6vN';
    public static $endpoint = 'oss-cn-beijing.aliyuncs.com';
    protected static $roleArn = 'acs:ram::1824667699712925:role/fubao999';//指定角色的 ARN ，角色策略权限

    public function __construct()
    {
        $ossConfig = Db::name('system_config')->where('group','upload')->select()->toArray();
        $ossConfig = array_column($ossConfig,'value','name');
        self::$ossBucket = $ossConfig['alioss_bucket']??'ferr-neo';
        self::$ossRegion = $ossConfig['alioss_endpoint']??'oss-cn-beijing.aliyuncs.com';
        self::$accessKeyId = $ossConfig['alioss_access_key_id']??'LTAI5tEUuTcqvvtcPCARvZcx';
        self::$accessKeySecret = $ossConfig['alioss_access_key_secret']??'n2cCzSPb3e3oKioTe5VgIlUppmB9Ec';
        self::$endpoint = $ossConfig['alioss_domain']??'oss-cn-beijing.aliyuncs.com';
//        self::$roleArn = $smsConfig['alisms_access_key_secret']??'oyIzSGMHJNGcTwbaHW9Po2ZIoDiCZh';
    }

    public static function getClient()
    {
        return new OssClient(self::$accessKeyId, self::$accessKeySecret, self::$endpoint);
    }

    public function getAuth()
    {
        $user_info = $this->checkToken();
        $authType = Request::param('authType');
        $dirName = '';
        $fileName = '';
        switch ($authType) {
            case 'sign':
                $dirName = 'user-sign';
                $fileName = "{$user_info['id']}.png";
                break;
            case 'user-avatar':
                $dirName = 'avatar';
                $fileName = "{$user_info['id']}.png";
                break;
            case 'user-pay':
                $order_id = (int)(Request::param('order_id'));
                if (!($order_id > 0)) {
                    return json_encode(['success' => false]);
                }
                $dirName = "user-pay/{$user_info['id']}/{$order_id}";
                $fileName = date('YmdHis') . ".png";
                break;
            case 'wxpay-receipt-code':
                $dirName = 'wxpay-receipt-code';
                $fileName = "wxpay-{$user_info['id']}-" . uniqid() . ".png";
                break;
            case 'alipay-receipt-code':
                $dirName = 'alipay-receipt-code';
                $fileName = "alipay-{$user_info['id']}-" . uniqid() . ".png";
                break;
            default:
                return json_encode(['success' => false]);


        }
       $data =  self::getStsAuth($dirName.'/'.$fileName);
        $res['region'] = 'oss-cn-beijing';
        $res['endpoint'] = 'oss-cn-beijing.aliyuncs.com';
        $res['bucket'] = 'ferr-neo';
        $res['accessKeyId'] = $data['Credentials']['AccessKeyId'];
        $res['accessKeySecret'] =  $data['Credentials']['AccessKeySecret'];
        $res['stsToken'] = $data['Credentials']['SecurityToken'];
        $res['filepath'] = $dirName.'/'.$fileName;

        return ['success' => true, 'data' => $res];die;
//        $this->result_ok('ok',$res);
//        try {
////            $ossClient = new OssClient($this->accessKeyId, $this->accessKeySecret, $this->endpoint);
//            $ossClient = self::getClient();
//            $ossClient->
//            $bucket = 'ferr-neo';
//            $data = $ossClient->uploadFile($bucket, uniqid(), "{$dirName}/{$fileName}");
//            return json_encode(['success' => true, 'data' => $data]);
//        } catch (OssException $e) {
////            print $e->getMessage();
//            $this->result_error($e->getMessage());
//        }


    }
    public static function getStsAuth($filepath)
    {
        AlibabaCloud::accessKeyClient(self::$accessKeyId, self::$accessKeySecret)
            ->regionId('oss-cn-beijing')
            ->asDefaultClient();
        try {

            $result = AlibabaCloud::rpc()
                ->product('Sts')
                ->scheme('https') // https | http
                ->version('2015-04-01')
                ->action('AssumeRole')
                ->method('POST')
                ->host('sts.aliyuncs.com')
                ->options([
                    'query' => [
                        'RegionId' => "oss-cn-beijing",
                        'RoleArn' => self::$roleArn,
                        'RoleSessionName' => uniqid(),
//                        'Policy' =>'{"Statement": [{"Action": ["oss:PutObject","oss:ListParts","oss:AbortMultipartUpload"],"Effect": "Allow","Resource":["acs:oss:*:*:ferr-neo/aa.png}]}],"Version":"1"}'
                        'Policy' =>'{"Statement": [{"Action": ["oss:PutObject","oss:ListParts","oss:AbortMultipartUpload"],"Effect": "Allow","Resource": ["acs:oss:*:*:ferr-neo/'.$filepath.'"]}],"Version":"1"}'
                    ],
                ])
                ->request();
            return $result->toArray();
        } catch (ClientException $e) {
            echo "ClientException"."\r\n";
            echo $e->getErrorMessage() . PHP_EOL;
        } catch (ServerException $e) {
            echo "ServerException"."\r\n";
            echo $e->getErrorMessage() . PHP_EOL;
        }
    }

}